/* eslint-disable import/no-anonymous-default-export */
import BIMApi from '@/services/bim'
import { v4 as uuidv4 } from 'uuid'
import { getUGM } from '@/utils/handlePrimitive'

export default {
  state: {
    data: {},
    bim: {},
    selectedIds: [],
    selectedStoreyIds: [],
    selectedRicentIds: [],
    idToEye: { ids: [], keys: {} },
    onlyToEye: { ids: [], keys: {} },
    stage: [],
    projectData: {},
    loadingVisible: false,
    ugmId: '',
    projectId: '',
    userType: '',
    ricentDrawing: {},
    ricentDrawingBackup: {},
    font: null,
    targetId: ''
  },
  // eslint-disable-next-line no-unused-vars
  effects: dispatch => ({
    async getData(payload, { graph }) {
      const { ugmId, projectData } = graph
      if (!ugmId) return
      if (projectData.docs && projectData.docs[ugmId] && projectData.docs[ugmId].url) {
        const url = projectData.docs[ugmId].url
        const NKey = uuidv4()
        const title = '请求盎锐云UGM数据'
        window.openNotification({ key: NKey, type: 'loading', title })
        const res = await BIMApi.getDataFromAil({ url })
        if (res && res.res_code === 0) {
          window.openNotification({ key: NKey, type: 'success', title })
          return res
        } else {
          window.openNotification({ key: NKey, type: 'error', title })
        }
      } else {
        const NKey = uuidv4()
        const title = '请求远程UGM数据'
        window.openNotification({ key: NKey, type: 'loading', title })
        const res = await BIMApi.getData({ ugmId: graph.ugmId })
        if (res && res.res_code === 0) {
          if (!res.architecture && !res.structure && !res.ugm) {
            window.openNotification({ key: NKey, type: 'warning', title: '获取远程UGM数据为空' })
          } else {
            window.openNotification({ key: NKey, type: 'success', title })
            return res
          }
        } else {
          window.openNotification({ key: NKey, type: 'error', title })
        }
      }
    },
    async saveData({ data, type }, { graph }) {
      if (data) {
        const NKey = uuidv4()
        const title = '请求远程服务器存储ugm数据'
        window.openNotification({ key: NKey, type: 'loading', title })
        const res = await BIMApi.saveData({ data, type, ugmId: graph.ugmId })
        if (res && res.res_code === 0) {
          window.openNotification({ key: NKey, type: 'success', title })
          return res
        } else {
          window.openNotification({ key: NKey, type: 'error', title })
        }
      }
    },
    async divideRoom({ stage, mergeList, type }, { graph }) {
      const NKey = uuidv4()
      const title = '分割房间算法'
      window.openNotification({ key: NKey, type: 'loading', title })
      const res = await BIMApi.divideRoom({ stage, ugmId: graph.ugmId, mergeList, type })
      if (res && res.res_code === 0) {
        window.openNotification({ key: NKey, type: 'success', title })
        return res
      } else {
        window.openNotification({ key: NKey, type: 'error', title })
      }
    },
    async planningScanstation({ points, stage, type }, { graph }) {
      const NKey = uuidv4()
      const title = '手动规划站点算法'
      window.openNotification({ key: NKey, type: 'loading', title })
      const ugm = getUGM({ data: graph.data, bim: graph.bim })
      const res = await BIMApi.planningScanstation({
        selectedIds: graph.selectedIds,
        points,
        stage,
        ugm,
        type,
        ugmId: graph.ugmId
      })
      if (res && res.res_code === 0) {
        window.openNotification({ key: NKey, type: 'success', title })
        return res
      } else {
        window.openNotification({ key: NKey, type: 'error', title })
      }
    },
    async getProject(payload, { graph }) {
      const NKey = uuidv4()
      const title = '从盎锐云获取项目信息'
      window.openNotification({ key: NKey, type: 'loading', title })
      let res
      if (!graph.ugmId && !graph.installmentId) {
        return
      }
      if (graph.userType === 'staff') {
        res = await BIMApi.queryByTaskId({ taskId: graph.ugmId })
        if (!res || res.status !== 1) {
          res = await BIMApi.queryByPlanningId({ planningId: graph.ugmId })
        }
      } else if (graph.userType === 'auditor') {
        res = await BIMApi.queryByInstallmentId({ installmentId: graph.installmentId })
      }
      if (res && res.status === 1) {
        window.openNotification({ key: NKey, type: 'success', title })
        const data = res.data
        const projectId = data.project_name[0]
        const projectData = {
          cols: {
            project: [
              {
                id: projectId,
                name: projectId,
                definition: 'project'
              }
            ],
            installment: data.project_stage.map(i => {
              return {
                id: i.installment_id,
                name: i.project_stage,
                project: projectId,
                definition: 'installment'
              }
            }),
            building: data.building.map(i => {
              return {
                id: i.building_id,
                name: i.building_num,
                installment: i.installment_id,
                recent_id: i.recent_bid,
                definition: 'building'
              }
            }),
            storey: data.storey.map(i => {
              const ugm = data.ugm.find(o => o.storey_id && o.storey_id.includes(i.storey_id))
              return {
                id: i.storey_id,
                name: i.storey_num,
                building: i.building_id,
                recent_id: i.recent_sid,
                ugm: ugm ? ugm.taskId : '',
                type: i.storey_type,
                definition: 'storey'
              }
            })
          }
        }
        projectData.cols.ugm = []
        data.ugm.forEach(i => {
          if (!projectData.cols.ugm.find(o => o.id === i.taskId)) {
            projectData.cols.ugm.push({
              id: i.taskId,
              name: i.name || i.taskId,
              url: i.ugm,
              taskState: i.taskState,
              definition: 'ugm',
              project: projectId
            })
          }
        })
        projectData.docs = {}
        for (const key in projectData.cols) {
          const col = projectData.cols[key]
          col.forEach(doc => (projectData.docs[doc.id] = doc))
        }
        if (projectData) {
          this.update({ projectData, projectId: projectData.cols.project[0].id, targetId: data[graph.ugmId] })
        } else {
          this.update({ projectId: projectData.cols.project[0].id })
        }
        return true
      } else {
        window.openNotification({ key: NKey, type: 'error', title })
        this.update({ projectData: {} })
        return false
      }
    },
    async getDrawingLayoutPoint(payload, { graph }) {
      const NKey = uuidv4()
      const { targetId, ugmId, projectData } = graph
      const id = targetId || ugmId
      if (projectData && projectData.cols && projectData.cols.storey.length && projectData.cols.ugm.length) {
        const ugm = projectData.cols.ugm.find(i => i.id === id)
        if (ugm && ugm.taskState === '已上传') {
          const storey = projectData.cols.storey.find(i => i.ugm === id)
          if (storey) {
            const title = '获取已上传瑞信图纸数据'
            window.openNotification({ key: NKey, type: 'loading', title })
            const res = await BIMApi.getDrawingLayoutPoint({ storeyId: storey.recent_id })
            if (res && res.status === 1) {
              window.openNotification({ key: NKey, type: 'success', title })
            } else {
              window.openNotification({ key: NKey, type: 'error', title })
            }
            return res
          }
        }
      }
    },
    async getDrawingLayoutPointFromBackup(payload, { graph }) {
      const NKey = uuidv4()
      const { targetId, ugmId, projectData } = graph
      const id = targetId || ugmId
      if (projectData && projectData.cols && projectData.cols.storey.length && projectData.cols.ugm.length) {
        const ugm = projectData.cols.ugm.find(i => i.id === id)
        if (ugm) {
          const storey = projectData.cols.storey.find(i => i.ugm === id)
          if (storey) {
            const title = '获取备份瑞信图纸数据'
            window.openNotification({ key: NKey, type: 'loading', title })
            const res = await BIMApi.getDrawingLayoutPointFromBackup({
              storeyId: storey.recent_id,
              drawingId: graph.targetId || graph.ugmId
            })
            if (res && res.status === 1) {
              window.openNotification({ key: NKey, type: 'success', title })
            } else {
              window.openNotification({ key: NKey, type: 'error', title })
            }
            return res
          }
        }
      }
    },
    async updateRoomsNumAndLayoutData(payload, { graph }) {
      const NKey = uuidv4()
      const { stageId, data } = payload
      const title = '更新户型名称和户型号'
      window.openNotification({ key: NKey, type: 'loading', title })
      const res = await BIMApi.updateRoomsNumAndLayoutData({
        drawingId: graph.targetId || graph.ugmId,
        stageId,
        data
      })
      if (res && res.status === 1) {
        window.openNotification({ key: NKey, type: 'success', title })
      } else {
        window.openNotification({ key: NKey, type: 'error', title })
      }
      return res
    }
  }),
  reducers: {
    update(prevState, payload) {
      return { ...prevState, ...payload }
    }
  }
}
